package com.driving.code.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.driving.code.entity.Answer;
import com.driving.code.entity.MyPage;
import com.driving.code.entity.ParseData;
import com.driving.code.entity.Question;
import com.driving.code.service.QuestionService;
import com.driving.code.utils.UploadUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@RestController
@RequestMapping("question")
public class QuestionController {
    @Resource
    private QuestionService questionService;
    @Resource
    private UploadUtils uploadUtils;

    /**
     * 获取下一题
     *
     * @param current
     * @return
     */
    @RequestMapping("getNextQuestionBySequence/{classify}/{current}/{flag}")
    public MyPage getNextQuestionBySequence(@PathVariable(value = "current") Integer current, @PathVariable(value = "classify") Integer classify, @PathVariable(value = "flag") String flag,HttpSession session) {
        IPage<Question> page = new Page(current, 1);
        IPage<Question> questionIPage = null;
        if ("sequence".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify));
        }
        if ("mistakable".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).ge(Question::getQuestionError, 10));
        }
        if ("uniterming".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionType, 1));
        }
        if ("multipleChoice".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionType, 3));
        }
        if ("trueOrFalse".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionType, 2));
        }
        if ("image".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).ne(Question::getQuestionImage, ""));
        }
        if (questionIPage == null) {
            return null;
        }
        List<Question> records = questionIPage.getRecords();
        Question question = records.get(0);
        session.setAttribute("questionId",question.getQuestionId());
        session.setAttribute("flag","0");
        MyPage<Question> myPage = new MyPage<>(questionIPage.getTotal(), questionIPage.getCurrent(), questionIPage.getRecords());
        return myPage;
    }

    /** 
     * 通过ID查询指定的问题
     *
     * @return
     */
    @RequestMapping("getNextQuestionById/{index}")
    public Question getNextQuestionById(@PathVariable(value = "index") Integer index, HttpSession session) {
        List<Integer> ids_random = (ArrayList<Integer>) session.getAttribute("ids_random");
        Integer id = ids_random.get(index);
        Question question = questionService.getById(id);
        session.setAttribute("questionId",question.getQuestionId());
        session.setAttribute("flag","0");
        return question;
    }

    /**
     * 获取全部的问题ID
     *
     * @param classify
     * @return
     */
    @RequestMapping("getAllQuestionIdsBySequence/{classify}/{flag}")
    public List<Integer> getAllQuestionIdsBySequence(@PathVariable(value = "classify") Integer classify, @PathVariable(value = "flag") String flag) {
        List<Question> list = null;
        if ("sequence".equals(flag)) {
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify));
        }

        if ("mistakable".equals(flag)) {
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).ge(Question::getQuestionError, 10));
        }

        if ("uniterming".equals(flag)) {
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionType, 1));
        }

        if ("multipleChoice".equals(flag)) {
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionType, 3));
        }

        if ("trueOrFalse".equals(flag)) {
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionType, 2));
        }
        if ("image".equals(flag)) {
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).ne(Question::getQuestionImage, ""));
        }

        ArrayList<Integer> arrayList = new ArrayList<>();
        for (Question question : list) {
            arrayList.add(question.getQuestionId());
        }
        return arrayList;
    }

    /**
     * 获取全部的ID，并打乱，模拟随机查询。
     *
     * @param classify
     * @return
     */
    @RequestMapping("getAllQuestionIdsByRandom/{classify}")
    public List<Integer> getAllQuestionIdsByRandom(@PathVariable(value = "classify") Integer classify, HttpSession session) {
        List<Integer> ids = this.getAllQuestionIdsBySequence(classify, "sequence");
        Collections.shuffle(ids);
        session.setAttribute("ids_random", ids);
        return ids;
    }

    /**
     * 获得全部的问题
     *
     * @param current
     * @param size
     * @param search
     * @return
     */
    @RequestMapping("getAllQuestion")
    public ParseData getAllQuestion(@RequestParam(value = "page", required = false, defaultValue = "1") Integer current,
                                    @RequestParam(value = "limit", required = false, defaultValue = "12") Integer size,
                                    @RequestParam(value = "search", required = false) String search,
                                    @RequestParam(value = "classify", required = false) Integer classify) {
        IPage<Question> page = new Page(current, size);
        LambdaQueryWrapper<Question> queryWrapper = new QueryWrapper<Question>().lambda();
        if (search != null && !search.equals("")) {
            queryWrapper.like(Question::getQuestionTopic, search);
        }
        if (classify != null) {
            queryWrapper.eq(Question::getQuestionClassify, classify);
        }
        IPage<Question> questionIPage = questionService.page(page, queryWrapper);
        ParseData<Question> parseData = new ParseData<>();
        parseData.setData(questionIPage.getRecords());
        parseData.setCode(0);
        parseData.setCount(questionIPage.getTotal());
        parseData.setMsg("请求成功");
        return parseData;
    }


    /**
     * 添加问题
     *
     * @param question
     * @return
     */
    @RequestMapping("addQuestion")
    public String addQuestion(Question question) {
        if (question.getQuestionType() == 2 && (!question.getQuestionC().equals("") || !question.getQuestionD().equals("") || !question.getQuestionE().equals("") ||
                !question.getQuestionF().equals("") || !question.getQuestionG().equals(""))) {
            return "2";
        }
        Answer answer = question.getAnswer();
        StringBuffer questionAnswer = new StringBuffer();
        if (answer.getQuestionAnswerA() != null && !answer.getQuestionAnswerA().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerA());
        }
        if (answer.getQuestionAnswerB() != null && !answer.getQuestionAnswerB().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerB());
        }
        if (answer.getQuestionAnswerC() != null && !answer.getQuestionAnswerC().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerC());
        }
        if (answer.getQuestionAnswerD() != null && !answer.getQuestionAnswerD().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerD());
        }
        if (answer.getQuestionAnswerE() != null && !answer.getQuestionAnswerE().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerE());
        }
        if (answer.getQuestionAnswerF() != null && !answer.getQuestionAnswerF().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerF());
        }
        if (answer.getQuestionAnswerG() != null && !answer.getQuestionAnswerG().equals("")) {
            questionAnswer.append(answer.getQuestionAnswerG());
        }
        if (questionAnswer.toString().length() > 1 && (question.getQuestionType() == 1 || question.getQuestionType() == 2)) {
            return "3";
        }
        question.setQuestionAnswer(questionAnswer.toString());
        boolean save = questionService.save(question);
        if (save) {
            return "1";
        }
        return "0";
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @RequestMapping("uploadImage")
    public ParseData uploadImage(MultipartFile file) {
        String location = uploadUtils.upload(file);
        ParseData parseData = new ParseData();
        parseData.setMsg(location);
        return parseData;
    }

    /**
     * 设置考试的试题
     *
     * @param questionId
     * @param questionTest
     * @return
     */
    @RequestMapping("setQuestionTest")
    public String setQuestionTest(Integer questionId, Boolean questionTest) {
        Question question = questionService.getById(questionId);
        question.setQuestionTest(questionTest);
        boolean b = questionService.updateById(question);
        if (b) {
            return "1";
        }
        return "0";
    }

    @RequestMapping("setQuestion")
    public String setQuestion(String field,Integer questionId,String question ) {
        Question question1 = questionService.getById(questionId);
        switch (field){
            case "questionA": question1.setQuestionA(question);break;
            case "questionB": question1.setQuestionB(question);break;
            case "questionC": question1.setQuestionC(question);break;
            case "questionD": question1.setQuestionD(question);break;
        }
        boolean b = questionService.saveOrUpdate(question1);
        if (b){
            return "1";
        }
       return "0";
    }

    @RequestMapping("importQuestion")
    public String importQuestion(String path) {
        StringBuilder stringBuilder = new StringBuilder("C:\\Users\\admin\\Desktop\\");
        stringBuilder.append(path).append(".xls");
        FileInputStream fs = null;
        HSSFWorkbook hssfWorkbook = null;
        try {
            fs = new FileInputStream(stringBuilder.toString());
            POIFSFileSystem ps = new POIFSFileSystem(fs);
            hssfWorkbook = new HSSFWorkbook(ps);
        } catch (IOException e) {
            return "0";
        }
        try {
            int number = hssfWorkbook.getNumberOfSheets();
            HSSFSheet sheet = null;
            boolean error = false;
            for (int j = 0; j < number; j++) {
                sheet = hssfWorkbook.getSheetAt(j);
                int lastRowNum = sheet.getLastRowNum();
                ArrayList<String> strings = new ArrayList<>();
                for (int i = 1; i <= lastRowNum; i++) {
                    HSSFRow row = sheet.getRow(i);
                    if (row != null) {
                        strings = new ArrayList<>();
                        for (Cell cell : row) {
                            if (cell != null) {
                                cell.setCellType(CellType.STRING);
                                String value = cell.getStringCellValue();
                                strings.add(value);
                            }
                        }
                        Question question=null;
                        try {
                            question = new Question(strings.get(1), strings.get(2), strings.get(3), strings.get(4), strings.get(5), strings.get(6), strings.get(7), Integer.valueOf(strings.get(8)), strings.get(9), strings.get(10));
                             questionService.save(question);
                        }catch (Exception e){
                            error=true;
                            System.out.println("第"+i+"条记录异常");
                        }
                    }
                }
            }
            if (error){
                return "3";
            }
                return "1";


        } catch (NumberFormatException e) {
            return "2";
        }

    }



    /**
     * 获得考试问题的全部ID
     *
     * @param classify
     * @return
     */
    @RequestMapping("getTestQuestionIds/{classify}")
    public List<Question> getTestQuestionIds(@PathVariable(value = "classify") Integer classify) {
        List<Question> list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionTest, true));
        Collections.shuffle(list);
        return list;
    }

    /**
     * 获得考试的试题
     *
     * @param current
     * @param classify
     * @return
     */
    @RequestMapping("getTestQuestion/{classify}/{current}")
    public MyPage getTestQuestion(@PathVariable(value = "current") Integer current, @PathVariable(value = "classify") Integer classify) {
        IPage<Question> page = new Page<>(current, 1);
        IPage<Question> questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionTest, true));
        MyPage<Question> myPage = new MyPage<>(questionIPage.getTotal(), questionIPage.getCurrent(), questionIPage.getRecords());
        return myPage;
    }
    /**
     * 删除问题
     *
     * @param questionId
     * @return
     */
    @RequestMapping("deleteQuestion")
    public String deleteQuestion(Integer questionId) {
        boolean delete = questionService.removeById(questionId);
        if (delete) {
            return "0";
        }
        return "1";
    }

    //编辑题目
    @RequestMapping("updateQuestion")
    public String updateQuestion(Integer questionId, String questionTopic, String questionAnswer, String questionType) {
        Question byId = questionService.getById(questionId);
        boolean flag = true;
        byId.setQuestionTopic(questionTopic);
        if (questionAnswer != null && !("").equals(questionAnswer)) {
            if (questionType.equals("3")) {   //如果题型为多选题，答案必须是ABCD选项
                char[] chars = questionAnswer.toCharArray();
                for (char c : chars) {
                    if (c != 'A' && c != 'B' && c != 'C' && c != 'D') {
                        flag = false;
                        break;
                    }
                }
            } else { //若为单选题，答案必须是ABCD其中一个
                if (!"A".equals(questionAnswer) && !"B".equals(questionAnswer) && !"C".equals(questionAnswer) && !"D".equals(questionAnswer)) {
                    return "2";
                }
            }
            if (flag) {
                byId.setQuestionAnswer(questionAnswer);
            } else
                return "3";
        }
        boolean b = questionService.saveOrUpdate(byId);
        if (b) {
            return "0";
        }
        return "1";
    }


    /**
     * 如果用户回答错误，当前问题的错误数量加一。
     *
     * @param questionId
     */
    @RequestMapping("questionError")
    public String questionError(Integer questionId) {
        Question question = questionService.getById(questionId);
        question.setQuestionError(question.getQuestionError() + 1);
        boolean b = questionService.updateById(question);
        if (b) {
            return "1";
        }
        return "0";
    }


    /**
     * 设置科目一的考试  限时时间
     *
     * @param request
     * @param time_limit
     * @return
     */
    @RequestMapping("subjectOneTestTime")
    @ResponseBody
    public String subjectOneTestTime(HttpServletRequest request, Integer time_limit) {
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("time_limit_one", time_limit);
        return "1";
    }

    /**
     * 设置科目四的考试  限时时间
     *
     * @param request
     * @param time_limit
     * @return
     */
    @RequestMapping("subjectFourTestTime")
    @ResponseBody
    public String subjectFourTestTime(HttpServletRequest request, Integer time_limit) {
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("time_limit_four", time_limit);
        return "1";
    }
    @RequestMapping("setSubjectOneFraction")
    @ResponseBody
    public String setSubjectOneFraction(HttpServletRequest request, Integer fraction) {
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("fraction", fraction);
        return "1";
    }
    @RequestMapping("setSubjectFourFraction")
    @ResponseBody
    public String setSubjectFourFraction(HttpServletRequest request, Integer fraction4) {
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("fraction4", fraction4);
        return "1";
    }
}

